【问题标题】:vector<string> declaration in c++C++中的vector<string>声明
【发布时间】:2017-12-18 03:59:02
【问题描述】:

我对 c++ 很陌生,所以很抱歉,如果这个解决方案非常琐碎。我在这个网站上搜索解决方案,但没有找到任何东西。 我需要做一些热力学演算,因此用一些信息来初始化我的课程。由于我的components_i,此代码在我编译时中断。 我正在寻找一种将向量传递给我的班级的方法,或者另一种方法来为班级中的微积分提供有关我想要模拟的混合物的信息。

h-文件:

#ifndef BASE_H
#define BASE_H
#include <string> 
#include <vector>
#include <iostream>
using namespace std;

class Base
{
    public:
    vector<string> components_i;
    int nComp,nPhase;
    long double T,P,N_p_i,x_p_i;
    Base( vector<string>,int,int,long double,long double,long double );
};

#endif

作为 cpp:

#include "Base.h"

Base::Base( vector<string> components_i,int nComp, int nPhase, long double T, long double P, long double N_p_i ) {
    Base::components_i = components_i //e.g. H2O and Ethanol
    Base::nComp = nComp;
    Base::nPhase = nPhase;
    Base::T = T;
    Base::P = P;
    Base::N_p_i = N_p_i;
}

这根本不起作用,但我认为它更清楚地说明了我想要做什么

有什么建议吗?

【问题讨论】:

  • 静态成员变量的定义需要在类外部,而不是在成员函数内部。
  • 你真的希望components_i 成为static吗?
  • 你真的需要所有的成员变量都是public吗?哦,您不需要在成员函数中为它们加上 Base:: 前缀。
  • 在头文件中使用using namespace std; 也是一种不好的做法,因为它会传播到包含它的每个文件。
  • 不知道你想要实现的目标是什么,这是行不通的。我的意思是,你的语法很不寻常。我会在您的构造函数中执行其中一项:1. 初始化列表,MyClass(int _a, int _b) : a(_a), b(_b) { ... } 用于两个成员 a 和 b,2. 分配名称略有不同的项目,MyClass(int _a, int _b) { a = _a; b = _b; },3. 使用 this 指针,MyClass(int a, int b) { this-&gt;a = a; this-&gt;b = b; } -这些将是通常使用的语法。也就是说,请用实际的句子陈述您的问题。 “为了实现……我想……而我当前的代码在这里……产生了这个错误:……”

标签: c++ class vector methods


【解决方案1】:

你没有声明你的静态成员。静态成员需要在类声明之外显式声明,添加:

vector<string> Base::components_i;

完整的代码应该是这样的:

#include <stdio.h>
#include <string> 
#include <vector>
#include <iostream>
using namespace std;

class Base
{
    public:
        static vector<string> components_i;
        int nComp,nPhase;
        long double T,P,N_p_i,x_p_i;
        Base( vector<string>,int,int,long double,long double,long double );
};

vector<string> Base::components_i;

Base::Base(vector<string> components_i,int nComp, int nPhase, long double T, long double P, long double N_p_i ) {
    Base::components_i = components_i; //e.g. H2O and Ethanol
    Base::nComp = nComp;
    Base::nPhase = nPhase;
    Base::T = T;
    Base::P = P;
    Base::N_p_i = N_p_i;
};

int main() {
    vector<string> vec;
    vec.push_back(string("hello"));
    Base base = Base(vec, 1, 1, 2.0, 2.0, 3.0);
    printf("%s", Base::components_i[0].c_str());
}

这是一个工作示例:

http://cpp.sh/9xkfk

【讨论】:

  • 很多
  • 鉴于 components_i 已在构造函数中设置,它可能实际上不应该是静态的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多