【发布时间】:2012-01-18 04:00:22
【问题描述】:
这是我的代码:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
template <class T1, class T2>
void copy2(const T1 source[], T2 destination[] , int size){
for (int i=0 ; i < size ; ++i){
destination[i]=static_cast<T1>(source[i]);
}
}
int main() {
const char one[] = "hello";
char two[5];
cout << "one: " << one << endl;
cout << "two: " << two << endl;
copy2(one, two, 6);
cout << "one: " << one << endl;
cout << "two: " << two << endl;
return 0;
}
但它输出:
一:你好
二:
一个:
二:你好
此外,数组“one”是常量,因此不应更改。
PS:当我以以下方式启动数组“二”时,它可以工作(但为什么??):
char two[8];
但是,当我以以下两种方式启动它时,我会收到奇怪的错误:
char two[6];
或
char two[7];
【问题讨论】:
-
您同时拥有
copy2和copyStuff。是哪个? -
对不起,我拼错了。但这不是问题。
-
数组
one是const,是的,但这并不意味着它不能被修改。这意味着尝试这样做是未定义的行为。
标签: c++ arrays templates copy char