J*****n 发帖数: 4859 | 1 class A {
public:
A(const string& _name):Name(_name) {}
const string Name;
};
class B:public A {
public:
B():A("It is B")
};
现在我有C
class C:public B
如何使C.Name成为“It is C”
谢谢 |
X****r 发帖数: 3557 | 2 Don't do it.
If you really want, use const_cast
class C : public B {
public:
C() : B() {
const_cast(name) = "It is C";
}
};
But it is a bad idea to begin with.
【在 J*****n 的大作中提到】 : class A { : public: : A(const string& _name):Name(_name) {} : const string Name; : }; : class B:public A { : public: : B():A("It is B") : }; : 现在我有C
|
h**********c 发帖数: 4120 | 3 应该可以
说不清,JAVA也可以这么干。
#include
#include
class A {
public:
A(const std::string& _name):Name(_name) {}
const std::string Name;
const std::string getName () {
return Name;
}
};
class B:public A {
public:
B():A("It is B") {}
const std::string getName () {
return Name;
}
};
class C:public B {
public:
const std::string Name;
C():Name("It is C") {}
const std::string getName () {
return Name;
}
};
int main () {
A a("It is A");
B b;
C c;
std::cout<
std::cout<
std::cout<
std::cout<
std::cout<
std::cout<
return 0;
}
【在 J*****n 的大作中提到】 : class A { : public: : A(const string& _name):Name(_name) {} : const string Name; : }; : class B:public A { : public: : B():A("It is B") : }; : 现在我有C
|
h*****f 发帖数: 248 | 4 Or you can use the "name hiding feature":
class C : public B {
public:
const std::string Name;
C() : Name("It is C") {}
};
C c;
c.Name will give you "It is C". |
f*******n 发帖数: 12623 | 5 This is completely different. He does not want to override a method. He
wants to pass an argument to A's constructor.
【在 h**********c 的大作中提到】 : 应该可以 : 说不清,JAVA也可以这么干。 : #include : #include : class A { : public: : A(const std::string& _name):Name(_name) {} : const std::string Name; : const std::string getName () { : return Name;
|
f*******n 发帖数: 12623 | 6 You can't, because C is a subclass of B. So a C object "is a" B object, so
must follow B's requirements. B objects always pass "It is B" to A's
constructor.
【在 J*****n 的大作中提到】 : class A { : public: : A(const string& _name):Name(_name) {} : const string Name; : }; : class B:public A { : public: : B():A("It is B") : }; : 现在我有C
|