简单的函数重载问题

时间:2011-02-19 22:08:31

标签: c++ overloading

设定功能的想法:

第一个参数是一个引用,分配空间来保存测试副本,将beany的str成员设置为指向新块,将测试复制到新块,并设置beany的ct成员。

问题:

1)包含以下内容的行

for (int i = 0; i < temp.length(); i++)
  

错误:表达式必须有一个类   型

2)包含以下内容的行

temp[i] = cstr[i];
  

错误:表达必须有   指向对象类型

3)由于存在const

,函数show()对于stringy类型的重载找不到匹配的函数签名

这些概念很新,有人可以解释错误的原因吗?

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <cstring>
#include <cctype>
struct stringy {
    char * str; //points to a string
    int ct; //length of string(not counting '\0')
};

void set(stringy & obj,  char cstr);
void show(const stringy & obj, int times=1);
void show(const char * cstr, int times = 1);

int _tmain(int argc, _TCHAR* argv[])
{
    string beany;
    char testing[] = "Reality isn't what it used to be.";

    set(beany, testing);
    show(beany);
    show(beany, 2);
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);
    show(testing, 3);
    show("Done");
    return 0;
}

void set(stringy & obj, char cstr)
{
    char * temp = new char[cstr];
    obj.str = temp;
    for (int i = 0; i < temp.length(); i++)
    temp[i] = cstr[i];
}

void show(const stringy & obj, int times)
{
    for (int i = 0; i < times; i++)
        cout << obj.str;
}

void show(const char * cstr, int times)
{
    for (int i = 0; i < times; i++)
        cout << cstr;
}

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

temp是一个const char *。该类型不提供任何类型的长度设施 - 它不是对象,也没有length()成员方法。使用std::string - 就是这样。

相关问题