我有一个派生自另一个的类,我使用一个基类指针数组来保存派生类的实例,但由于该数组属于基类,我无法使用指针表示法访问属于派生类的成员,我可以通过一个简单的命令访问这些成员,或者我应该只重写我的基类来定义成员并只在派生类中使用它?
例:
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++的初学者,我有一个关于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"的情况下,输出不会打印正确的答案.
我怎么解决这个问题 ?
我有一个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)