我想实现一个成员与此函数匹配的类:
int get(
string &host_,
string &port_,
string url_path,
ostream &out_,
vector<string> &headers,
unsigned int timeout
)
我有这个:
#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <ostream>
#include "Register.h"
using namespace std;
class Request : public Register {
private:
string *host;
string *port;
string *url;
ostream *out;
vector<string> *header;
unsigned int *timeout;
public:
Request() {
this -> host = new string();
this -> port = new string();
this -> url = new string();
this -> out = new ostream();
this -> header = new vector<string>();
this -> timeout = new int();
}
但我无法实例化它。 例如,ostream是怎么回事:
this -> out = new ostream();
我仍然是 c++ 的新手,现在我完全困惑了,我在 Google 上找不到正确的答案。
std::ostream
是特定流实现的基类,如std::ofstream
,你不能直接实例化它。
在C++中,与Java不同,我们不会在堆上分配所有内容,而是更喜欢值语义:
/// Can be easily copied
class HoldSomething {
private:
std::string name;
std::vector<std::string> values;
public:
/// constructors
HoldSomething() : name(), values() {}
explicit HoldSomething( const std::string& name ) :
name( name ), values() {}
/// modifiers
void addValue( const std::string& val ) {
value.push_back( val );
}
...
您应该发布您遇到的错误。 std::ostream
只是界面;你不能煽动它。
我认为您在引用和指针之间感到困惑。 该函数接受向量和标头、字符串 &host_ 等引用。 您的类存储的指针不是一回事。
如果你正常地将变量传递到函数中(签名中没有 * 或 &),那么你就会创建你传入的东西的副本。 这就是"逐个副本传递"。 如果传入指针 (*),则传递的内容指向要使用的变量的内存地址。 从技术上讲,您是通过副本传递指针的,但它指向同一件事,所以你没关系。 如果传入引用 (&),则会从调用函数的作用域中为变量设置别名。 你说"我想像通过副本一样对待这个变量,除了我希望更改也适用于最初从外部范围传递到函数中的变量"。
因此,您的类可以改为包含普通成员:
private:
string host;
string port;
string url;
ostream out;
vector<string> header;
unsigned int timeout;
这样,您就可以将它们直接传递给函数而不会出现问题。 在这种情况下,它们也将是默认构造的,因此您无需使用"new"或执行任何操作。 事实上,你甚至不需要编写构造函数。
请注意,您可能需要一个访问器函数来允许您修改所有这些函数,因为您将它们设为私有,或者您需要使构造函数采用参数,以便在使用结构之前为数据成员提供有用的值。
PS:您想使用std::ofstream代替您的输出:) 在下面的链接中查看以下示例:
http://www.cplusplus.com/doc/tutorial/files/
std::ostream 只是一个接口您可以通过"std::cout"或派生自 std::ostream 的另一个具体对象来初始化"out"指针。例如:
out = &std::cout;
或
std::ofstream file("file.txt");
out = &file;
顺便说一下,使用普通指针是个坏主意。尝试任何智能指针,如 std::shared_ptr 或 std::unique_ptr。