【发布时间】:2012-06-10 20:33:47
【问题描述】:
对于一个项目,我试图设置一个链表对象,以便可以使用显式值构造函数对其进行初始化。我希望它看起来像这样:
WORD you("you");//where the object you's linked list now contains y o u;
但是当我打印出你的对象时,我看到的只是这个符号“=” 当我打印出你的长度时,我得到 -858993459
这是我的显式值构造函数,谁能告诉我我做错了什么?
WORD::WORD(string s)
{
front = 0;
int i = 0;
int len = s.length();
if(front == 0)
{
front = new alpha_numeric;
alpha_numeric *p = front;
while(s[i] <= len)
{
p -> symbol = s[i];
p -> next = new alpha_numeric;
p = p -> next;
p -> symbol = s[i++];
}
p -> next = 0;
}
}
如果有帮助,这里是类声明文件
#include <iostream>
#include <string>
using namespace std;
#pragma once
class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};
class WORD
{
public:
WORD(); //front of list initially set to Null
WORD(const WORD& other);
WORD(string s); //***EXPLICIT VALUE CONSTRUCTOR
bool IsEmpty(); //done
int Length();
void Add(char); //done
//void Insert(WORD bword, int position);
//void operator=(char *s);
friend ostream & operator<<(ostream & out, const WORD& w);//done
private:
alpha_numeric *front; //points to the front node of a list
int length;
};
【问题讨论】:
-
我认为您要查找的术语是
conversion constructor。显式构造函数有explicit关键字,不能像你的那样进行隐式转换。 -
我会先从你的标题中删除
using namespace std;。与#include <iostream>相同,在声明类时不需要包含它 - 将其移至处理流的 .cpp。 -
还有
front = 0;和if(front == 0)紧随其后。干什么用的? -
你为什么不直接委托给你自己的
Add()方法呢?干燥。 -
对。为什么不能从构造函数本身调用
Add()?
标签: c++ linked-list explicit-constructor