【发布时间】:2019-01-27 11:08:04
【问题描述】:
我必须将类Parameters 的重载构造函数放入类Solver 的函数中。
这是参数标题:
#ifndef Parameters
#define Parameters
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;
class Parameters
{
int M;
double dx;
double eps;
public:
Parameters( );
Parameters(int M1, double dx1, double eps1 );
Parameters( string fileName);
};
#endif
构造函数初始化M、dx、eps 使用默认值或由用户从键盘或文件中选择。
我想要另一个包含这个初始化值的类(为了解决最近的一些方程,也在这个类中)。
问题是,虽然我尝试通过值、引用或/指针来做到这一点,但总是有一些错误或代码编译但什么也没做。
这是我的 Solver 类:
#include "ParametersH.h"
#include "EquationH.h"
#include <iostream>
#include<conio.h>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
class Solver
{
public:
int Solve( Parameters& obj );
};
int Solver::Solve( Parameters& obj)
{
cout << obj.M; // M is private so it fails :<
// another attempt was like this:
Parameters *pointer = new Parameters();
}
int main()
{
Solver Solve();
return( 0 );
}
我真的无法处理这个,希望有人能帮忙。
【问题讨论】:
-
Solver Solve();这声明了一个名为Solve()的函数,它没有返回一个Solver对象的参数。您可能希望将其更改为Solver solver; solver.Solve(existingParameterObject);。 -
@lubgr 但是参数类对象只是一个重载的构造函数......你能更广泛地解释一下我应该放什么吗?
-
Solver::Solve(Parameters& obj)的参数不是构造函数,而是Parameters类型的对象。因此,您必须先构建它。 -
@lubgr 这里:Solver::Solve(Parameters& obj) 参数代表类的名称,对吗?类Parameters的对象类型是指M,dx,eps的类型,因为构造函数Parameters填充它们?所以我必须在 M、dx、eps 等类型的 Solver 类中构造对象?
-
@JeJo 我试图通过朋友班做到这一点,但失败了。错误是“在非类类型'int'的'obj'中请求成员M(来自类参数的私有变量)。
标签: c++ function class c++11 constructor