gpt4 book ai didi

c++ - C++编译错误中vector的模板

转载 作者:行者123 更新时间:2023-11-28 05:54:14 24 4
gpt4 key购买 nike

这是我使用的代码:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Vector
{
// Use user defined template class for vector handling
template <class V,class D>
void vec_add(V &vec, D data)
{
vec.push_back(data);
}
};

int main ()
{
vector<int> v; // v is vecor of int elements

Vector.vec_add(&v,222);
}

目标:定义一个通用的项目添加到任何类型的 vector 。
问题:我遇到编译错误。

最佳答案

有很多问题:

首先,将成员函数设为public:

class Vector  
{
public:

其次,

Vector.vec_add(&v,222);

应该是这样的

 Vector foo;
foo.vec_add(v,222);

因为您传递的是引用,而不是指针,并且您必须在实例上调用成员函数,在本例中为 foo,因为成员函数不是static(想想你是否想让它成为static,在这种情况下你调用它作为Vector::vec_add)。完整的工作代码如下:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Vector
{
public:
// Use user defined template class for vector handling
template <class V, class D>
void vec_add(V &vec, D data)
{
vec.push_back(data);
}
};

int main ()
{
vector<int> v; // v is vecor of int elements

Vector foo;
foo.vec_add(v, 222);
std::cout << v.front(); // test it
}

Live on Coliru

一个好的建议是从 here 中挑选一本书并学习该语言的基本特征。

关于c++ - C++编译错误中vector的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34569453/

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