我想我有数据切片的问题,但我不知道如何解决这个问题。
这里我只有一个子类 (B),但实际上我还有其他子类(没有 j
作为成员)。
这是我的代码:
helloworld.h
#ifndef HELLOWORLD_H_
#define HELLOWORLD_H_
class A {
public:
A(): i(5) {}
int i;
};
class B: public A {
public:
B(): A(), j(2) {}
int j;
};
#endif /* HELLOWORLD_H_ */
helloworld.cpp
#include <iostream>
#include <vector>
#include "helloworld.h"
using namespace std;
int main() {
vector<A*> v;
v.push_back(new B());
v.push_back(new B());
vector<A*>::iterator it = v.begin();
++it;
cout << (*it)->j;
return 0;
}
最佳答案
除了@interjay 的评论:
C++ 不是这样工作的。您的 A
类不知道子类将拥有什么类型的变量,因此它无法访问它们。您可以改用虚函数。
标题:
#ifndef HELLOWORLD_H_
#define HELLOWORLD_H_
class A {
public:
A(): i(5) {}
virtual int GetJ () const = 0 ;
private:
int i;
};
int A::GetJ () const {
// Throw exception or return an error.
}
class B: public A {
public:
B(): A(), j(2) {}
int GetJ () const ;
private:
int j;
};
int B::GetJ () const {
return j ;
}
#endif /* HELLOWORLD_H_ */
主要内容:
#include <iostream>
#include <vector>
#include "helloworld.h"
using namespace std;
int main()
{
vector<A*> v;
v.push_back(new B());
v.push_back(new B());
vector<A*>::iterator it = v.begin();
cout << (*it)->GetJ () ;
// Don't forget to clean up memory allocations,
// or better yet, use smart pointers.
return 0;
}
关于c++ - 找不到子类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20361938/