0

在使用 Visual Studio 2008 的本机 C++ 中,如何使用 const 将接口传递给类成员?执行以下操作会导致此错误:

错误 C2662:“IMyInterface::PublicMember1”无法将“this”指针从“const IMyInterface”转换为“IMyInterface &”

class IMyInterface
{
  virtual std::wstring PublicMember1() = 0;
  virtual int PublicMember2() = 0;
  virtual void Update(const IMyInterface & myObject) = 0;
}

class MyClass : public IMyInterface
{
   private:
      std::wstring privateMember1;
      int privateMember2;
   public:
      virtual std::wstring PublicMember1() { return privateMember1; }
      virtual int PublicMember2() { return privateMember2; }
      virtual void Update(const IMyInterface & myObject);
}

void MyClass::Update(const IMyInterface& myObject)
{
     privateMember1 = myObject.PublicMember1();
     privateMember2 = myObject.PublicMember2();
}
4

1 回答 1

10

将接口所需的方法声明为const

class IMyInterface
{
  virtual std::wstring PublicMember1() const = 0;
  virtual int PublicMember2() const = 0;
  virtual void Update(const IMyInterface & myObject) = 0;
}
于 2012-07-25T11:28:56.820 回答