小编Ste*_*hen的帖子

从基类的指针访问派生类的成员

我有一个派生自另一个的类,我使用一个基类指针数组来保存派生类的实例,但由于该数组属于基类,我无法使用指针表示法访问属于派生类的成员,我可以通过一个简单的命令访问这些成员,或者我应该只重写我的基类来定义成员并只在派生类中使用它?

例:

class A {
public:
    int foo;
};

class B : public A {
public:
    char bar;
};

class C : public A {
    int tea;
};

int main() {
    A * arr[5];
    arr[0] = new B;

    char test = arr[0]->bar; //visual studio highlights this with an error "class A has no member bar"

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ polymorphism pointers class

5
推荐指数
1
解决办法
583
查看次数

c ++中的简单数组求和

我是C++的初学者,我有一个关于c ++中简单求和代码的问题.

这是我的代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main()
{
    int n;
    int sum;
    int arr_i = 0;

    cin >> n;
    vector<int> arr(n);
    while (arr_i != n)
    {
        cin >> arr[arr_i];
        sum += arr[arr_i];
        //cout << sum << endl;
        if (arr_i == n - 1)
            cout << sum;
        arr_i++;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在if条件之前没有"cout << sum"的情况下,输出不会打印正确的答案.

我怎么解决这个问题 ?

c++ sum

2
推荐指数
1
解决办法
1043
查看次数

调整std :: vector <std :: atomic_bool>的大小,为所有原子bool赋值true

我有一个std::vector<std::atomic_bool>我想要调整到一些任意的n,其中所有新创建的对象都被赋值为true.程序不会构建,因为它resize()依赖于数据类型的复制构造函数,而不是它的赋值运算符.有没有办法为一个默认值分配一个atomic_bool或者我会坚持使用循环和store()所有的值?

我尝试过的:

#include <atomic>
#include <vector>

class foo() {
public:
    std::vector<std::atomic_bool> vec;

    foo() {
        std::atomic_bool temp(true);

        vec.resize(100, std::atomic_bool(true)); //try 1

        vec.resize(100, temp); //try 2
    }
}
Run Code Online (Sandbox Code Playgroud)

c++ vector atomic

2
推荐指数
1
解决办法
500
查看次数

标签 统计

c++ ×3

atomic ×1

class ×1

pointers ×1

polymorphism ×1

sum ×1

vector ×1