#include <iostream>
class Foo {
public:
int m_foo;
Foo(int a_foo) : m_foo(a_foo) {}
protected:
bool operator==(const Foo& a) const {
std::cout << "Foo: " << m_foo << " == " << a.m_foo << '\n';
return m_foo == a.m_foo;
}
};
class Bar : public Foo {
public:
int m_bar;
Bar(int a_foo, int a_bar) :
Foo(a_foo),
m_bar(a_bar)
{}
bool operator==(const Bar& a) const {
std::cout << "Bar: " << m_foo << ", " << m_bar << " == " << a.m_foo << ", " << a.m_bar << '\n';
return (const Foo&)*this == (const Foo&)a &&
m_bar == a.m_bar;
}
};
int main() {
Bar a(1, 1);
Bar b(1, 2);
Bar c(2, 2);
std::cout << (a == a) << '\n';
std::cout << (a == b) << '\n';
std::cout << (a == c) << '\n';
return 0;
}
使用受保護的==操作符在我真正的代碼Foo
是可以被實例化,但不應該被允許使用operator==
所以我把它protected
類。我得到這樣做的編譯器錯誤:不能在派生類中
foo.cpp: In member function ‘bool Bar::operator==(const Bar&) const’:
foo.cpp:9:7: error: ‘bool Foo::operator==(const Foo&) const’ is protected
bool operator==(const Foo& a) const {
^
foo.cpp:25:43: error: within this context
return (const Foo&)*this == (const Foo&)a &&
^
爲什麼不允許這樣做?派生類不應該能夠使用protected
方法嗎?
'回報(常量美孚&)*本==(常量美孚&)了' - 不知道,但是'=='似乎沒有在基類上運行。它是兩個獨立的對象,'* this'和'a'。 @MichaelBurr給出的答案實際上是在調用中使用基類「Foo ::'。 – PaulMcKenzie
@PaulMcKenzie,這種說法有道理,就好像它更像'operator ==(const Foo&l,const Foo&r)'簽名,但我會認爲'(const Foo&)* this' would have產生了一個'Foo',然後它的方法將被使用 – asimes
@PaulMcKenzie,我想了一下更多,並決定,因爲我沒有定義一個兩個對象相等運算符,應該沒有一個函數/方法來比較兩個對象。仍然困惑,雖然 – asimes