我创建了一个名为 Student 的类,如下所示:
class Student
{
private:
unsigned int id; // the id of the student
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
Student(unsigned int init_val) {id = init_val;}; // constructor
~Student() {}; // destructor
};
然后在我想要一个容器(比如一个 vector )之后,它的元素是 Student 类的实例,但我发现自己无法理解这种情况,这是我的问题:
首先我运行这段代码:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
Student ver_list[2] = {7, 9};
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver_list[1].get_id() << endl;
return 0;
}
一切都很好,输出是:
Hello, This is a code to learn classes
9
现在当我尝试这些选项时:
选项#1:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
vector <Student> ver[N]; // Create vector with N elements
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i);
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver[1].get_id() << endl;
return 0;
}
我得到了这个输出“错误”:
test.cpp:26:3: error: expected unqualified-id before 'for'
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:26:27: error: 'i' does not name a type
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:26:34: error: expected unqualified-id before '++' token
for(unsigned int i = 0; i < N; ++i )
^
test.cpp: In function 'int main()':
test.cpp:43:15: error: 'class std::vector<Student>' has no member named 'get_id'
cout<< ver[1].get_id() << endl;
^
选项#2:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
Student ver[N]; // Create one dimensional array with N elements
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i);
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver[1].get_id() << endl;
return 0;
}
输出“错误”是:
test.cpp:30:14: error: no matching function for call to 'Student::Student()'
Student ver[5];
^
test.cpp:30:14: note: candidates are:
test.cpp:14:2: note: Student::Student(unsigned int)
Student(unsigned int init_val) {id = init_val;}; // constructor
^
test.cpp:14:2: note: candidate expects 1 argument, 0 provided
test.cpp:7:7: note: Student::Student(const Student&)
class Student
^
test.cpp:7:7: note: candidate expects 1 argument, 0 provided
test.cpp:31:1: error: expected unqualified-id before 'for'
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:31:25: error: 'i' does not name a type
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:31:32: error: expected unqualified-id before '++' token
for(unsigned int i = 0; i < N; ++i )
^
在第一次尝试时一切看起来都很好,但是当我尝试接下来的两个选项时,我收到了错误,我希望我能理解我做错了什么。
谢谢。
最佳答案
这个:
vector <Student> ver[N];
创建 N 的数组元素。每个元素都是 vector<Student> .这不是你想要的。您可能正在尝试创建 N 的 vector 元素。语法是:
vector <Student> ver(N);
但是你不能使用它,因为你的类没有默认构造函数。因此,您的下一个替代方案是使用相同的元素初始化所有对象。
vector <Student> ver(N, Student(0));
您还尝试创建一个这样的学生数组:
Student ver[N];
这是行不通的。因为它试图用默认构造函数初始化数组中的每个元素。但是您的类没有默认构造函数。所以这行不通。但这就是您的原始代码确实有效的原因:
Student ver_list[2] = {7, 9}; // Here you are using the constructor for your object.
// It uses the normal constructor you provided not the default one.
另一个问题是你不能在函数(方法)之外运行代码。
所以这是行不通的:
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i);
在 C++11 中,您可以像初始化数组一样初始化 vector :
vector<Student> ver = { 0, 1, 2, 3, 4, 5};
如果您没有 C++11 或初始化更复杂。然后你需要写一个包装器。
class VecWrapper
{
public:
std::vector<Student> ver;
VecWrapper()
{
ver.reserve(N);
for(unsigned int i = 0; i < N; ++i )
ver.push_back(Student(i));
}
};
现在你可以把它放在全局范围内,它会自动初始化。
VecWrapper myData; // myData.vec initializaed before main entered.
int main()
{}
选项 2:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
// The following is not correct
// This creates an arrya of `N` elements each element is `vector <Student>`
//
// vector <Student> ver[N]; // Create vector with N elements
//
// The following lines are not allowed.
// All code has to be inside a function.
//
// for(unsigned int i = 0; i < N; ++i )
// ver[i].set_id(i);
// What you want is:
// I use the following because it is unclear if you have C++11 or not.
class VecWrapper
{
public:
std::vector<Student> vec;
VecWrapper()
{
vec.reserve(N);
for(unsigned int i = 0; i < N; ++i )
vec.push_back(Student(i));
}
};
VecWrapper myData; // myData.vec
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< myData.vec[1].get_id() << endl;
return 0;
}
关于c++ - 在 C++ 中创建类实例的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19657728/
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案
我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_
我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。
我正在尝试找出如何为我的Ruby项目创建一种“无类DSL”,类似于在Cucumber步骤定义文件中定义步骤定义或在Sinatra应用程序中定义路由。例如,我想要一个文件,其中调用了我的所有DSL函数:#sample.rbwhen_string_matches/hello(.+)/do|name|call_another_method(name)end我认为用我的项目特有的一堆方法污染全局(内核)命名空间是一种不好的做法。因此方法when_string_matches和call_another_method将在我的库中定义,并且sample.rb文件将以某种方式在我的DSL方法的上下文中
有这些railscast。http://railscasts.com/episodes/218-making-generators-in-rails-3有了这个,你就会知道如何创建样式表和脚手架生成器。http://railscasts.com/episodes/216-generators-in-rails-3通过这个,您可以了解如何添加一些文件来修改脚手架View。我想把两者结合起来。我想创建一个生成器,它也可以创建脚手架View。有点像RyanBates漂亮的生成器或web_app_themegem(https://github.com/pilu/web-app-theme)。我
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Rubysyntaxquestion:Rational(a,b)andRational.new!(a,b)我正在阅读ruby镐书,我对创建有理数的语法感到困惑。Rational(3,4)*Rational(1,2)产生=>3/8为什么Rational不需要new方法(我还注意到例如我可以在没有new方法的情况下创建字符串)?
如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是: