c++ - 找不到子类的成员

标签 c++ vector iterator

我想我有数据切片的问题,但我不知道如何解决这个问题。 这里我只有一个子类 (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/

相关文章:

ruby - 这个 ruby 迭代器棘手的干净解决方案?

c++ - 流接口(interface)的抽象(二进制只读输入源)

c++ - SFML 2.0:Keyboard::isKeyPressed 并不总是正确返回

c++ - move 的 vector 总是空的吗?

c++ - 使用 -std=gnu++11 开关编译时出现 std::equal 错误

python迭代器通过带有子列表的树

c++ - BFS : Trouble in accessing adjacency lists 的 STL 实现

c++ - 使用 join() 从不同范围运行 C++ 线程

c++ - 如何从函数返回 vector 引用?

iterator - Rhs 在有关 PartialEq 的编译器错误消息中指的是什么?