我是 Objective-C 的新手,所以如果这在语言中本质上不起作用,请原谅,但它似乎应该这样做。我想要做的是以英寸为单位计算书籍对象的厚度。以下是 Book
中的对象头文件:
NSString *title, *author;
int *numPages;
/**
* The thickness of any given page in the book, in inches (e.g. 20lb stock would be 0.0038)
*/
double *pageThickness;
bool *hasHardCover;
63 -(int *)calculateWidthInInches
64 {
65 return (((double *)numPages) *
66 pageThickness) +
67 (hasHardCover ? 0.25 :
68 (pageThickness * 4.0));
69 }
/Users/student4/Downloads/LibraryOfBooks/Book.m:66: error: invalid operands to binary * (have 'double *' and 'double *')
/Users/student4/Downloads/LibraryOfBooks/Book.m:68: error: invalid operands to binary * (have 'double *' and 'double')
/Users/student4/Downloads/LibraryOfBooks/Book.m:69: warning: control reaches end of non-void function
calculateWidthInInches
做错了什么方法? 63 -(double)calculateWidthInInches
64 {
65 return ((*numPages) * *pageThickness) + (*hasHardCover ? 0.25 : (*pageThickness * 4.0));
66 }
最佳答案
您所有的变量都是指针,而不是值。编译器提示您试图将指针相乘,这是一个没有意义的操作。
您需要在相乘之前取消引用指针,以便将值相乘,而不是值的地址。
编辑:另外,正如 Yuras 指出的那样,直接转换指针并不是一个好主意——取消引用指针,然后转换值:
-(double)calculateWidthInInches
{
return (((double)*numPages) *
pageThickness) +
(*hasHardCover ? 0.25 :
(*pageThickness * 4.0));
}
https://stackoverflow.com/questions/9072243/