gpt4 book ai didi

c++ - 无法解析符号 vector

转载 作者:太空宇宙 更新时间:2023-11-04 15:22:06 25 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

using namespace std;


class block{
public:
long nx,ny;
vector<long> s;
block(long &x, long &y):nx(x),ny(y),vector<long> s((x+1)*(y+1),0) {}
};

int main() {
block B(2,2);
for(int i=1;i<=9;i++) {
cout<<B.s(i);
}

cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}

已编译,错误消息显示无法解析符号“vector”。错误是什么?我想定义一个包含要初始化的可变维度 vector 的类。


#include <iostream>
#include <vector>

using namespace std;


class block{
public:
long nx,ny;
vector<long> s;
block(long &x, long &y):nx(x),ny(y),s((x+1)*(y+1),0) {}
};

int main() {
block B(2,2);
for(int i=0;i<=9;i++) {
cout<<B.s[i];
}

cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}

在 block B(2,2) 仍然有问题;错误信息:构造函数“block::block”的实例与参数列表不匹配

为什么?谢谢!

最佳答案

首先:

  vector<long> s((x+1)*(y+1),0)

应该是:

  s((x+1)*(y+1),0)

不应为 重复类型。同时构造函数应该是:

  block(const long &x, const long &y):
nx(x), ny(y), s((x + 1) * (y + 1), 0)
{
}

如果你真的需要引用。因为否则,当你这样做的时候

 block B(2,2);

main 中,它会给你错误,因为构造函数采用 long&,你传递的是 int 常量。深层原因与左值和右值有关:整型常量是右值,而 long& 是对非常量 long 的引用,是左值引用。根据这个博客:lvalues, rvalues and references

An lvalue reference (to non-const type) is a reference that can be initialized with an lvalue. Well, only with those lvalues that do not render const or volatile types. An rvalue reference (to non-const type) is a reference that can be initialized with an rvalue (again, only with those rvalues that do not designate const or volatile types). An lvalue reference to const type is a reference that can be initialized with rvalues and lvalues alike (rendering constant and non-constant types).

此外,根据 C++11 标准:第 4.1 节标准转换:

Standard conversions are implicit conversions defined for built-in types. A standard conversion sequence is a sequence of standard conversions in the following order:

— Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.

— Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.

— Zero or one qualification conversion.

没有右值到左值的转换。这就是您看到编译错误的原因。在 long& 之前添加 const 使其能够使用右值进行初始化,这就是更改后错误消失的原因。

其次,

  cout<<B.s(i);

应该是:

cout<<B.s[i];

您应该使用 [] 来访问 vector 元素。

第三, vector 索引从0开始,所以

for(int i=1;i<=9;i++)

应该是

for(int i=0;i<9;i++)

否则索引越界。请在此处查看工作示例:http://ideone.com/YLT3mG

关于c++ - 无法解析符号 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com